package pl.freetimetool.service;

import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import pl.freetimetool.dao.HolidaysInPolandDao;

@Transactional
@Repository
public class HolidaysInPolandServiceImpl implements HolidaysInPolandService {
	
	@Autowired
	HolidaysInPolandDao holidaysInPolandDao;
	
	@Override
	public int workingDaysBetween (Date startDate, Date endDate){
		
		int daysBetween = 0; 
		GregorianCalendar startCal = new GregorianCalendar(new Locale("PL"));
		GregorianCalendar endCal = new GregorianCalendar(new Locale("PL"));
		startCal.setTime(startDate);
		endCal.setTime(endDate);
		
		if(endCal.before(startCal)){
			throw new IllegalArgumentException("end date can't be before start date.");
		}
		
		while (startCal.before(endCal) || startCal.equals(endCal)) {
			
			if (!isWeekendDay(startCal) 
					&& !holidaysInPolandDao.isPolishHoliday(startCal.getTime()) ) {
				daysBetween++;
			}
			startCal.add(Calendar.DAY_OF_MONTH, 1);
		}
		
		return daysBetween;
	}
	
	@Override
	public boolean isPolishHoliday(Date dateToCheck){
		return holidaysInPolandDao.isPolishHoliday(dateToCheck);
	}
	
	@Override
	public boolean isPolishHoliday(String dateToCheck) throws ParseException{
		return holidaysInPolandDao.isPolishHoliday(dateToCheck);
	}
	
	public boolean isWeekendDay(Calendar dateToCheck){
		int dayOfWeek = dateToCheck.get(Calendar.DAY_OF_WEEK);
		
		if (dayOfWeek == Calendar.SATURDAY || dayOfWeek == Calendar.SUNDAY) {
			return true;
		}
		
		return false;
	}
}
